#include "app.h"

#include <sstream>

#include <tbox/base/log.h>
#include <tbox/base/defines.h>
#include <tbox/event/timer_event.h>

namespace your {

App::App(tbox::main::Context &ctx)
 : Module("your", ctx)
 , timer_event_(ctx.loop()->newTimerEvent())
{
  ros_ = new RosBridge(ctx, *this);
  add(ros_);
}

App::~App() {
  CHECK_DELETE_RESET_OBJ(timer_event_);
}

bool App::onInit(const tbox::Json &cfg) {
  initShell();
  timer_event_->initialize(std::chrono::seconds(1), tbox::event::TimerEvent::Mode::kPersist);
  timer_event_->setCallback(
    [this] () {
      count_++;
      ros_->pubText("Hello, cpp-tbox_sample ! " + std::to_string(count_));
    }
  );

  using namespace std;
  cout
    << "Try cmd:" << endl
    << " telnet localhost 50000                                 # talk with me." << endl
    << " echo '/your/hello; quit' | nc localhost 50001          # send command to me." << endl
    << " ros2 topic echo topic_text                             # see the published messages." << endl
    << " ros2 topic pub topic_bool std_msgs/Bool 'data: true    # publish bool topic." << endl
  ;

  return true;
}

bool App::onStart() {
  timer_event_->enable();
  return true;
}

void App::onStop() {
  timer_event_->disable();
}

void App::onCleanup() { }

void App::on_Ros_ready() {
  LogInfo("RosBridge is ready!");
}

void App::on_Ros_gotBool(bool value) {
  LogInfo("Received bool value: %s", value ? "true" : "false");
}

void App::on_Ros_addTwoInts(int a, int b, std::promise<int> &result) {
  ctx().thread_pool()->execute(
    [a, b, &result] {
      LogDbg("calculating ...");
      //! 这里模拟计算需要2秒才能得到答案，真实的情况可是别的，比如：写文件、规划路径
      std::this_thread::sleep_for(std::chrono::seconds(2));

      auto sum = a + b;
      LogDbg("%d + %d = %d", a, b, sum);
      result.set_value(sum);
    }
  );
}

}
